package com.duanjc.resiliencepatterns.service;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryRegistry;
import io.github.resilience4j.timelimiter.TimeLimiter;
import io.github.resilience4j.timelimiter.TimeLimiterRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class Resilience4jEventListener {

    private static final Logger logger = LoggerFactory.getLogger(Resilience4jEventListener.class);

    private final RetryRegistry retryRegistry;
    private final TimeLimiterRegistry timeLimiterRegistry;
    private final CircuitBreakerRegistry circuitBreakerRegistry;
    private final RateLimiterRegistry rateLimiterRegistry;

    @Autowired
    public Resilience4jEventListener(CircuitBreakerRegistry circuitBreakerRegistry,
                                     RateLimiterRegistry rateLimiterRegistry,
                                     RetryRegistry retryRegistry,
                                     TimeLimiterRegistry timeLimiterRegistry) {
        this.circuitBreakerRegistry = circuitBreakerRegistry;
        this.rateLimiterRegistry = rateLimiterRegistry;
        this.retryRegistry = retryRegistry;
        this.timeLimiterRegistry = timeLimiterRegistry;
    }

    @PostConstruct
    public void postConstruct() {

        //  注册 Retry 事件监听器
        Retry retry = retryRegistry.retry("retryService");
        retry.getEventPublisher()
                .onEvent(event -> logger.info("Retry event: {}", event));

        // 注册 CircuitBreaker 事件监听器
        CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("circuitbreakerService");
        circuitBreaker.getEventPublisher()
                .onEvent(event -> logger.info("CircuitBreaker Event: {}", event));

        // 注册 RateLimiter 事件监听器
        RateLimiter rateLimiter = rateLimiterRegistry.rateLimiter("ratelimiterService");
        rateLimiter.getEventPublisher()
                .onEvent(event -> logger.info("RateLimiter Event: {}", event));

        // 注册 TimeLimiter 事件监听器
        TimeLimiter timeLimiter = timeLimiterRegistry.timeLimiter("timeoutService");
        timeLimiter.getEventPublisher()
                .onEvent(event -> logger.info("TimeLimiter Event: {}", event));
    }

}
